import { useCounterStore } from '@/stores/counter'

class SocketManager {
  constructor(options = {}) {
    this.url = options.url || 'ws://localhost:8080/ws'
    this.reconnectInterval = options.reconnectInterval || 3000
    this.heartbeatInterval = options.heartbeatInterval || 30000
    this.maxReconnectAttempts = options.maxReconnectAttempts || 5
    this.uid = options.uid || ''
    this.token = options.token || ''
    this.live_id = options.live_id || ''
    this.reconnectAttempts = 0
    this.heartbeatTimer = null
    this.reconnectTimer = null
    this.ws = null
    this.messageCallbacks = new Map()
    this.isConnected = false
    this.isReconnecting = false
  }

  // 初始化WebSocket连接
  connect() {
    try {
      this.ws = new WebSocket(this.url)
      this.initEventHandlers()
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.reconnect()
    }
  }

  // 初始化WebSocket事件处理
  initEventHandlers() {
    const store = useCounterStore()
    this.ws.onopen = () => {
      console.log('WebSocket连接成功')
      this.isConnected = true
      this.isReconnecting = false
      this.reconnectAttempts = 0
      if (this.reconnectTimer) {
        clearTimeout(this.reconnectTimer)
        this.reconnectTimer = null
      }
      this.startHeartbeat()
      this.messageCallbacks.get('connect')?.forEach(callback => callback())
    }

    this.ws.onclose = () => {
      console.log('WebSocket连接关闭')
      this.isConnected = false
      this.isReconnecting = false
      this.stopHeartbeat()
      this.messageCallbacks.get('close')?.forEach(callback => callback())
      this.reconnect()
    }

    this.ws.onerror = (error) => {
      console.error('WebSocket错误:', error)
      this.messageCallbacks.get('error')?.forEach(callback => callback(error))
    }

    this.ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data)
        if (data.m === 'pong') {
          // 处理心跳响应
          store.viewerCount = data.on_num
          return
        }
        this.messageCallbacks.get('message')?.forEach(callback => callback(data))
      } catch (error) {
        console.error('消息解析错误:', error)
      }
    }
  }

  // 重连机制
  reconnect() {
    if (this.isReconnecting || this.reconnectAttempts >= this.maxReconnectAttempts) return

    this.isReconnecting = true
    this.reconnectTimer = setTimeout(() => {
      console.log(`尝试重连... (${this.reconnectAttempts + 1}/${this.maxReconnectAttempts})`)
      this.reconnectAttempts++
      this.connect()
    }, this.reconnectInterval)
  }

  // 心跳机制
  startHeartbeat() {
    this.stopHeartbeat()
    this.send({ type: 'ping' })
    this.heartbeatTimer = setInterval(() => {
      if (this.isConnected) {
        this.send({ type: 'ping' })
      }
    }, this.heartbeatInterval)
  }

  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
      this.heartbeatTimer = null
    }
  }

  // 发送消息
  send(data) {
    if (!this.isConnected) {
      console.warn('WebSocket未连接')
      return false
    }

    try {
      const message = typeof data === 'string' ? data : JSON.stringify({
        ...data,
        'uid': this.uid,
        "token": this.token,
        "live_id": this.live_id
      })
      this.ws.send(message)
      return true
    } catch (error) {
      console.error('发送消息失败:', error)
      return false
    }
  }

  // 注册事件监听
  on(event, callback) {
    if (!this.messageCallbacks.has(event)) {
      this.messageCallbacks.set(event, new Set())
    }
    this.messageCallbacks.get(event).add(callback)
  }

  // 移除事件监听
  off(event, callback) {
    if (this.messageCallbacks.has(event)) {
      if (callback) {
        this.messageCallbacks.get(event).delete(callback)
      } else {
        this.messageCallbacks.delete(event)
      }
    }
  }

  // 关闭连接
  close() {
    this.stopHeartbeat()
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer)
      this.reconnectTimer = null
    }
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    this.isConnected = false
    this.isReconnecting = false
  }
}

// 创建单例
let instance = null

export const createSocket = (options) => {
  if (!instance) {
    instance = new SocketManager(options)
  }
  return instance
}

export default createSocket 